import CommonDrawer from '@/components/CommonDrawer';
import request from '@/utils/request';
import { useAsyncEffect, useRequest } from 'ahooks';
import { Form, Tabs } from 'antd';
import BaseInfo from './BaseInfo';
import StationInfo from './StationInfo';
import TrackInfo from './TrackInfo';

const Save = (props) => {
  const { open, record: recordProps, onCancel, onOk } = props;
  const [baseInfoForm] = Form.useForm();
  const { data, runAsync, mutate } = useRequest(
    async (params) => {
      const url = recordProps ? '/datas/line/update' : '/datas/line/add';
      const res = await request({
        url,
        method: 'POST',
        data: params,
      });
      return res;
    },
    { manual: true },
  );
  const { data: detailData, runAsync: runAsyncDetail } = useRequest(
    async (params) => {
      const res = await request({
        url: '/datas/line/detail',
        method: 'GET',
        params,
      });
      return res;
    },
    { manual: true },
  );
  const record = data ? { lineId: data } : recordProps;

  useAsyncEffect(async () => {
    if (open && recordProps) {
      const res = await runAsyncDetail({
        lineId: recordProps.lineId,
      });
      baseInfoForm.setFieldsValue(res);
    }
  }, [open, recordProps]);
  const items = [
    {
      key: '1',
      label: '线路信息',
      children: (
        <BaseInfo record={record} form={baseInfoForm} request={runAsync} />
      ),
    },
    ...(record
      ? [
          {
            key: '2',
            label: '站点信息',
            children: (
              <StationInfo
                lineId={record?.lineId}
                value={detailData?.stations}
              />
            ),
          },
          {
            key: '3',
            label: '轨迹信息',
            children: <TrackInfo lineId={record?.lineId} />,
          },
        ]
      : []),
  ];
  console.log('datadatadata', data);
  return (
    <CommonDrawer
      title={record ? '编辑' : '新建'}
      open={open}
      onClose={onCancel}
      afterOpenChange={(visible) => {
        if (!visible) {
          baseInfoForm.resetFields();
          mutate();
        }
      }}
      width={1400}
      footer={null}
      destroyOnHidden
      styles={{
        body: {
          paddingTop: 0,
        },
      }}
    >
      <Tabs items={items} className="fit-tabs" />
    </CommonDrawer>
  );
};

export default Save;
